using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;

namespace DocumentCreationSystem
{
    /// <summary>
    /// 章节修复工具
    /// 用于检查和修复项目中不完整或格式错误的章节内容
    /// </summary>
    public class RunChapterRepair
    {
        public static async Task Main(string[] args)
        {
            Console.WriteLine("=== 章节内容修复工具 ===");
            Console.WriteLine();

            try
            {
                // 获取项目路径
                string projectPath;
                if (args.Length > 0)
                {
                    projectPath = args[0];
                }
                else
                {
                    Console.Write("请输入项目路径（默认为 '诡异收藏家'）: ");
                    var input = Console.ReadLine();
                    projectPath = string.IsNullOrWhiteSpace(input) ? "诡异收藏家" : input;
                }

                // 转换为绝对路径
                if (!Path.IsPathRooted(projectPath))
                {
                    projectPath = Path.Combine(Environment.CurrentDirectory, projectPath);
                }

                Console.WriteLine($"项目路径: {projectPath}");

                if (!Directory.Exists(projectPath))
                {
                    Console.WriteLine($"错误: 项目路径不存在: {projectPath}");
                    return;
                }

                // 创建服务容器
                var host = CreateHost();
                await host.StartAsync();

                using var scope = host.Services.CreateScope();
                var repairService = scope.ServiceProvider.GetRequiredService<ChapterContentRepairService>();
                var logger = scope.ServiceProvider.GetRequiredService<ILogger<RunChapterRepair>>();

                Console.WriteLine();
                Console.WriteLine("开始检查章节质量...");

                // 检查章节质量
                var problematicChapters = await repairService.CheckProjectChapterQualityAsync(projectPath);

                if (problematicChapters.Count == 0)
                {
                    Console.WriteLine("✓ 所有章节内容质量良好，无需修复");
                    return;
                }

                Console.WriteLine($"发现 {problematicChapters.Count} 个需要修复的章节:");
                foreach (var chapter in problematicChapters)
                {
                    Console.WriteLine($"  - {Path.GetFileName(chapter)}");
                }

                Console.WriteLine();
                Console.Write("是否开始修复这些章节？(y/N): ");
                var confirm = Console.ReadLine();

                if (confirm?.ToLower() != "y" && confirm?.ToLower() != "yes")
                {
                    Console.WriteLine("操作已取消");
                    return;
                }

                Console.WriteLine();
                Console.WriteLine("开始修复章节...");

                // 执行修复
                var repairResult = await repairService.RepairProjectChaptersAsync(projectPath);

                Console.WriteLine();
                Console.WriteLine("=== 修复结果 ===");
                Console.WriteLine($"总处理数量: {repairResult.TotalProcessed}");
                Console.WriteLine($"修复成功: {repairResult.RepairedChapters.Count}");
                Console.WriteLine($"修复失败: {repairResult.FailedChapters.Count}");

                if (repairResult.RepairedChapters.Count > 0)
                {
                    Console.WriteLine();
                    Console.WriteLine("成功修复的章节:");
                    foreach (var chapter in repairResult.RepairedChapters)
                    {
                        Console.WriteLine($"  ✓ {chapter}");
                    }
                }

                if (repairResult.FailedChapters.Count > 0)
                {
                    Console.WriteLine();
                    Console.WriteLine("修复失败的章节:");
                    foreach (var chapter in repairResult.FailedChapters)
                    {
                        Console.WriteLine($"  ✗ {chapter}");
                    }
                }

                Console.WriteLine();
                Console.WriteLine(repairResult.IsSuccess ? "✓ 修复完成" : "⚠ 修复过程中遇到问题");
                Console.WriteLine(repairResult.Message);

                await host.StopAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
                Console.WriteLine($"详细信息: {ex}");
            }

            Console.WriteLine();
            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
        }

        private static IHost CreateHost()
        {
            return Host.CreateDefaultBuilder()
                .ConfigureServices((context, services) =>
                {
                    // 注册基础服务
                    services.AddSingleton<IDataStorageService, JsonDataStorageService>();
                    services.AddSingleton<IThinkingChainService, ThinkingChainService>();
                    services.AddSingleton<IThemeService, ThemeService>();
                    services.AddSingleton<IProjectHistoryService, ProjectHistoryService>();
                    services.AddSingleton<IFileNamingService, FileNamingService>();

                    // 注册AI服务
                    services.AddSingleton<IAIService>(provider =>
                        new AIServiceManager(
                            provider.GetRequiredService<Microsoft.Extensions.Configuration.IConfiguration>(),
                            provider.GetRequiredService<ILogger<AIServiceManager>>(),
                            provider.GetRequiredService<IThinkingChainService>(),
                            provider));

                    // 注册其他必要服务
                    services.AddScoped<IProjectService, ProjectService>();
                    services.AddScoped<IDocumentService, DocumentService>();
                    services.AddScoped<INovelCreationService, NovelCreationService>();
                    services.AddScoped<WorldSettingService>();
                    services.AddScoped<NetworkRecoveryService>();
                    services.AddScoped<ResumableCreationService>();

                    // 注册修复相关服务
                    services.AddScoped<ContentQualityService>();
                    services.AddScoped<StepByStepWritingService>();
                    services.AddScoped<ChapterContentRepairService>();

                    // 注册HttpClient
                    services.AddHttpClient();

                    // 配置日志
                    services.AddLogging(builder =>
                    {
                        builder.AddConsole();
                        builder.SetMinimumLevel(LogLevel.Information);
                    });
                })
                .Build();
        }
    }
}

/// <summary>
/// 使用说明：
/// 
/// 1. 直接运行（使用默认项目路径）：
///    dotnet run --project DocumentCreationSystem RunChapterRepair.cs
/// 
/// 2. 指定项目路径：
///    dotnet run --project DocumentCreationSystem RunChapterRepair.cs "D:\AI_project\文档管理及创作系统\诡异收藏家"
/// 
/// 3. 功能说明：
///    - 自动检查项目中所有章节文件的质量
///    - 识别不完整、格式错误或包含错误信息的章节
///    - 根据章节细纲重新生成完整的小说正文
///    - 自动备份原文件
///    - 提供详细的修复报告
/// 
/// 4. 修复标准：
///    - 移除AI思维链和错误信息
///    - 确保内容为标准小说正文格式
///    - 字数达到约6500字的标准
///    - 包含丰富的场景描写和人物对话
///    - 严格按照章节细纲发展情节
/// </summary>
